package com.sz.app.edi.exception;

import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.sz.app.edi.constants.EdiErrorCodes;
import com.sz.app.edi.rest.edi.base.Response;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.i18n.I18nMessages;
import com.sz.common.base.logger.Logger;
import com.sz.common.base.utils.SerializeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;

/**
 * Function: GlobalExceptionHandler <br>
 * Author: wentao.chang <br>
 * Date: 2016-10-25 14:11:00
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    Logger logger = Logger.getLogger(this.getClass());

    @ExceptionHandler(value = EdiException.class)
    public Response defaultErrorHandler(HttpServletRequest req, EdiException exception) throws Exception {
        exception.printStackTrace();
        return getExceptionDto(exception.getErrorCode(), exception.getMsg());
    }

    @ExceptionHandler(value = BizException.class)
    public Response bizErrorHandler(HttpServletRequest req, BizException exception) throws Exception {
        exception.printStackTrace();
        return getExceptionDto(exception.getErrorCode(), exception.getMsg());

    }

    @ExceptionHandler(value = UnrecognizedPropertyException.class)
    public Response unrecognizedPropertyExceptionHandlers(HttpServletRequest req, UnrecognizedPropertyException exception) throws Exception {
        exception.printStackTrace();
        EdiException ediException = EdiExceptions.ediException(EdiErrorCodes.ERROR_ARGUMENT);
        return getExceptionDto(ediException.getErrorCode(), ediException.getMsg());
    }


    @ExceptionHandler(value = Exception.class)
    public Response defaultErrorHandler(HttpServletRequest req, Exception exception) throws Exception {
        logger.error(SerializeUtil.logExceptionStack(exception));

        //500服务器内部错误
        return getExceptionDto(-1, "系统繁忙，请稍后重试");
    }


    private Response getExceptionDto(int code, String message) {
        Response response = new Response();
        response.setSuccess(false);
        response.setCode(code + "");
        response.setMsg(message);
        return response;
    }


}
